package com.ytjj.common.service;

import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPayUtil;
import com.ytjj.common.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @version 1.0
 *
 */
@Slf4j
public class WxUtils {

    private static final String WX_APPLET_MSGSECCHECK_URL = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=";

    private static final String WX_APPLET_GETTICKTE_URL = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=wx_card";

    private static final String WX_APPLET_LIVE_URL = "https://api.weixin.qq.com/wxa/business/getliveinfo?access_token=ACCESS_TOKEN";



    /**
     * 内容敏感词过滤
     *
     * @param accessToken
     * @param content
     * @return
     */
    public static JSONObject msgSecCheck(String accessToken, String content) {
        JSONObject param = new JSONObject();
        param.put("content", content);
        log.info("微信内容敏感词校验请求 ：{}", param.toString());
        // 发送请求
        String wxResult = HttpClientUtil.doPostJson(WX_APPLET_MSGSECCHECK_URL + accessToken, param.toJSONString());
        log.info("微信内容敏感词校验响应 ：{}", wxResult);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        return jsonObject;
    }
    /**
     * 获取小程序直播间列表
     *
     * @param accessToken
     * @return
     */
    public static JSONObject getLiveList(String accessToken,Map<String,Object> param) {
        // 发送请求
        String wxAppletGettickteUrl = WX_APPLET_LIVE_URL.replace("ACCESS_TOKEN",accessToken);
        String wxResult = HttpClientUtil.doPostJson(wxAppletGettickteUrl,JSONObject.toJSONString(param));
        log.info("微信直播间列表响应 ：{}", wxResult);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        return jsonObject;
    }


    /**
     * 获取微信会员卡 ticket
     *
     * @param accessToken
     * @return
     */
    public static JSONObject getTicket(String accessToken) {
        // 发送请求
        String wxAppletGettickteUrl = WX_APPLET_GETTICKTE_URL.replace("ACCESS_TOKEN",accessToken);
        String wxResult = HttpClientUtil.doGet(wxAppletGettickteUrl);
        log.info("微信会员卡ticket响应 ：{}", wxResult);
        JSONObject jsonObject = JSONObject.parseObject(wxResult);
        return jsonObject;
    }

    /**
     * 获取jsSdk
     *
     * @param jsapiTicket
     * @param url
     * @param appid
     * @return
     */
    public static Map<String,Object> getJsSdk(String jsapiTicket, String url,String appid) {
        Map<String,Object> data = new HashMap<>();
        data.put("timestamp",System.currentTimeMillis() / 1000 + "");
        data.put("nonceStr", WXPayUtil.generateNonceStr());
        data.put("appId",appid);
        data.put("signature",SHA1("jsapi_ticket="+jsapiTicket
                +"&noncestr="+data.get("nonceStr")
                +"&timestamp="+data.get("timestamp")
                +"&url="+url));
        List<String> jsList = Arrays.asList("updateAppMessageShareData",
                "updateTimelineShareData",
                "onMenuShareTimeline",
                "onMenuShareAppMessage",
                "onMenuShareQQ",
                "onMenuShareWeibo",
                "onMenuShareQZone",
                "startRecord",
                "stopRecord",
                "onVoiceRecordEnd",
                "playVoice",
                "pauseVoice",
                "stopVoice",
                "onVoicePlayEnd",
                "uploadVoice",
                "downloadVoice",
                "chooseImage",
                "previewImage",
                "uploadImage",
                "downloadImage",
                "translateVoice",
                "getNetworkType",
                "openLocation",
                "getLocation",
                "hideOptionMenu",
                "showOptionMenu",
                "hideMenuItems",
                "showMenuItems",
                "hideAllNonBaseMenuItem",
                "showAllNonBaseMenuItem",
                "closeWindow",
                "scanQRCode",
                "chooseWXPay",
                "openProductSpecificView",
                "addCard",
                "chooseCard",
                "openCard",
                "openAddress");
        data.put("jsApiList",jsList);
        return data;
    }

    public static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

    public static void main(String[] args) {
        getTicket("" +
                "37_hIRoMO_NSlRKt-lV2DNIX4-djhNqMYP1VRpD6ezlHk1gMTrUYclN7tVrUA3d2p4J2bKCCk1NBl5-uHlNah1ZJWcJCvy4cWOY9f4RijPFxjDhu_ir7qePgLDEFqZTIajExNhDD_svvXrcVmM1JVXgAGAXJL");
    }

}
